package br.inf.solutions.apresentacoes.ssp.control.validator;

import java.util.HashMap;
import java.util.Map;

import br.com.vexillum.util.Return;
import br.inf.solutions.apresentacoes.ssp.control.BaseController;
import br.inf.solutions.apresentacoes.ssp.model.basics.BasicCommon;

public abstract class BasicFormsValidator<E extends BasicCommon> extends BaseValidator {

	public BasicFormsValidator(Map<String, Object> mapData) {
		super(mapData);
	}
	
	@Override
	public Return validateSave() {
		Return ret = new Return(true);
		ret.concat(super.validateSave());
		ret.concat(existsName());
		return ret;
	}
	
	@Override
	public Return validateUpdate() {
		Return ret = new Return(true);
		ret.concat(super.validateUpdate());
		ret.concat(existsName());
		return ret;
	}
	
	@SuppressWarnings("unchecked")
	private Return existsName(){
		Return ret = new Return(true);
		HashMap<String, Object> data = new HashMap<String, Object>();
		E basic = (E) entity;
		
		String sql = "FROM " + basic.getClass().getSimpleName() + " WHERE name = '" + basic.getName() + "'";
		data.put("sql", sql);
		
		BaseController<E> controller = getController(data);
		if(!controller.searchByHQL().getList().isEmpty()){
			ret.concat(creatReturn(null, getValidationMessage(null, "existsname", true)));
		}
		return ret;
	}

	protected abstract BaseController<E> getController(HashMap<String, Object> data);
	
}
